package com.csaba.connector.service;

import java.lang.reflect.Field;

import com.csaba.connector.BankService;
import com.csaba.connector.DummyServer;
import com.csaba.connector.I18NServiceException;
import com.csaba.connector.ServiceException;
import com.csaba.connector.model.Customer;
import com.csaba.connector.model.Session;

/**
 * @author Gabe
 * AbstractBankService provides generic permission handling methods. It explores PERMISSION tags on the services and 
 * provides method to easily check the permission.
 * XXX use annotation
 */
public abstract class AbstractBankService implements BankService
{

	/**
	 * Returns permission that is required to execute this service. Override the method if 
	 * the required permission is depending on some parameter of the service.
	 * @return permission that is required to execute this service.
	 * @throws I18NServiceException 
	 */
	public String getPermission() throws I18NServiceException
	{
		try
		{
			final Class<?> clazz = getClass();
			final Field field = clazz.getField("PERMISSION");
			if ( field != null )
			{
				final String permission = (String) field.get(this);
				return permission;
			}
		}
		catch ( final NoSuchFieldException e )
		{
			// no permission is defined for this class, DO NOTHING
		}
		catch ( final Exception e )
		{
			throw new I18NServiceException(DummyServer.getInstance(), "msg.failedToGetPermissions", e, getClass()
					.getName());
		}
		return null;
	}

	/**
	 * Checks if the customer logged in the session has permission to execute this service.
	 * @param session 
	 * @throws ServiceException thrown if no permission is available
	 */
	@Override
	public void checkPermission( final Session session ) throws ServiceException
	{
		final String permission = getPermission();
		if ( permission == null )
			return; // service is not tied to any permission.

		if ( session == null )
			throw new I18NServiceException(DummyServer.getInstance(), "msg.noCustomerLoggedIn");

		final Customer customer = session.getCustomer();
		if ( customer == null )
			throw new I18NServiceException(DummyServer.getInstance(), "msg.noCustomerLoggedIn");

		if ( !customer.hasPermission(permission) && !customer.hasPermission(ALL_PERMISSION) )
			throw new I18NServiceException(DummyServer.getInstance(), "msg.missingPermission", (String) null,
					permission);
	}

}
